import {_decorator, Button, Component, Node, Sprite} from 'cc';
import {AudioManager} from "db://assets/scripts/common/AudioManager";
import {ResourceUtils} from "db://assets/scripts/common/ResourceUtils";
import {EventManager} from "db://assets/scripts/common/EventManager";
import {Skill} from "db://assets/scripts/data/model/Skill";
import {EventType} from "db://assets/scripts/common/EventType";
import {AudioPaths} from "db://assets/scripts/common/AudioPaths";

const {ccclass, property} = _decorator;

/**
 * 技能图标控制器
 */
@ccclass('SkillIconController')
export class SkillIconController extends Component {
    /**
     * 按钮
     */
    @property(Button)
    public comBtn: Button;
    /**
     * 图标
     */
    @property(Sprite)
    public iconSprite: Sprite;
    /**
     * 背景
     */
    @property(Node)
    public bgNode: Node;

    /**
     * 技能信息
     */
    private skill: Skill;
    /**
     * 选中
     */
    private selected: boolean = false;
    /**
     * 回调
     */
    private callback: Function;

    onEnable() {
        EventManager.on(EventType.HIDE_SKILL_ICON_SELECTED, this.hideSelected, this);
    }

    onDisable() {
        EventManager.off(EventType.HIDE_SKILL_ICON_SELECTED, this.hideSelected, this);
    }

    public init(index: number, itemInfo: Skill, callback?: Function) {
        this.skill = itemInfo;
        this.callback = callback;
        this.selected = false;

        // 第一个图标且回调不为空时
        if (index === 0 && this.callback) {
            this.showSelected();
            this.callback(this.skill);
        } else {
            this.hideSelected();
        }

        // 当有回调时
        if (callback) {
            this.comBtn.transition = Button.Transition.SCALE;
        } else {
            this.comBtn.transition = Button.Transition.NONE;
        }

        // 设置图片
        ResourceUtils.setSpriteFrame(`texture/skillIcon/${itemInfo.icon}`, this.iconSprite);
    }

    /**
     * 点击事件
     */
    public onClick() {
        // 播放声音
        AudioManager.getInstance().playSound(AudioPaths.clickSound);

        // 当选中此技能，并且有回调时
        if (!this.selected && this.callback) {
            // 分发事件
            EventManager.dispatchEvent(EventType.HIDE_SKILL_ICON_SELECTED);
            // 调用回调
            this.callback(this.skill);
            // 选中此技能
            this.showSelected();
        }
    }

    /**
     * 选中
     */
    private showSelected() {
        this.selected = true;
        this.bgNode.active = true;
    }

    /**
     * 未选中
     */
    private hideSelected() {
        this.selected = false;
        this.bgNode.active = false;
    }
}